<template>
  <view>
    <cu-custom bgColor="bg-blue" :isBack="true">
      <block slot="content">个人信息</block>
    </cu-custom>
    <view class="cu-form-group">
      <view class="title">头像</view>
      <view class="cu-avatar radius bg-gray" @click="chooseImage">
        <image
          :src="userInfoForUpd.avatar"
          mode="aspectFill"
          class="cu-avatar"
        ></image>
      </view>
    </view>
    <view class="cu-form-group">
      <view class="title">昵称</view>
      <input
        placeholder=""
        v-model="userInfoForUpd.nickname"
        class="text-gray"
      />
    </view>
    <view class="cu-form-group">
      <view class="title">邮箱</view>
      <input placeholder="" v-model="userInfoForUpd.email" class="text-gray" />
    </view>
    <view class="cu-form-group">
      <view class="title">电话</view>
      <input placeholder="" v-model="userInfoForUpd.phone" class="text-gray" />
    </view>
    <view class="cu-form-group">
      <view class="title">性别</view>
      <picker
        @change="handleUserGenderPickerChange"
        :value="userInfoForUpd.gender"
        :range="['男', '女', '保密']"
      >
        <view class="picker">
          {{ ["男", "女", "保密"][userInfoForUpd.gender] }}
        </view>
      </picker>
    </view>
    <view class="padding flex flex-direction"
      ><button @click="handleClickUpdate" class="cu-btn bg-blue lg">
        更新
      </button></view
    >
  </view>
</template>

<script>
import OSS from "@/lib/aliyun-oss-sdk-6.13.2.min.js";
import { checkTokenInStore } from "../../permission/index";
import { mapState, mapMutations } from "vuex";
import {
  updateUserInfoByIdApi,
  fetchUserInfoApi,
  fetchOssTokenApi,
} from "../../api/http.js";
import urls from "../../api/urls";
export default {
  data() {
    return {
      userInfoForUpd: {
        id: null,
        nickname: "",
        email: "",
        phone: "",
        gender: true,
        avatar: "",
      },
      imgInfo: null,
    };
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.userInfo,
      token: (state) => state.token,
    }),
  },
  onLoad() {
    checkTokenInStore();
  },
  onShow() {
    this.copyUserInfo();
  },
  methods: {
    ...mapMutations(["setUserInfo"]),
    copyUserInfo() {
      const info = this.userInfo;
      this.userInfoForUpd.id = info.id;
      this.userInfoForUpd.nickname = info.nickname;
      this.userInfoForUpd.email = info.email;
      this.userInfoForUpd.phone = info.phone;
      this.userInfoForUpd.gender = info.gender;
      this.userInfoForUpd.avatar = info.avatar;
    },
    handleUserGenderPickerChange(e) {
      this.userInfoForUpd.gender = e.detail.value;
    },
    handleClickUpdate() {
      this.updateUserInfo();
    },
    updateUserInfo() {
      updateUserInfoByIdApi(this.userInfoForUpd).then((res) => {
        fetchUserInfoApi({
          token: this.token,
        }).then((res2) => {
          this.setUserInfo(res2.data);
          uni.showToast({
            icon: "success",
            title: "更新成功",
          });
        });
      });
    },
    chooseImage() {
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album"], //从相册选择
        success: (res) => {
          this.imgInfo = res;
          this.uploadImage();
        },
      });
    },
    uploadImage() {
      fetchOssTokenApi().then((res) => {
        const tokenInfo = res.data;
        let client = new OSS({
          region: tokenInfo.region,
          accessKeyId: tokenInfo.accessKeyId,
          accessKeySecret: tokenInfo.accessKeySecret,
          stsToken: tokenInfo.securityToken,
          bucket: tokenInfo.bucket,
        });
        //上传文件
        const name = this.imgInfo.tempFiles[0].name;
        let strs = name.split(".");
        const filename = tokenInfo.uuid + "." + strs[strs.length - 1];
        let curTime = new Date();
        let year = curTime.getFullYear(),
          month = curTime.getMonth() + 1,
          day = curTime.getDate();
        let dir =
          year +
          "/" +
          (month < 10 ? "0" + month : month) +
          "/" +
          (day < 10 ? "0" + day : day) +
          "/";
        this.h5UrlToBlob(this.imgInfo.tempFilePaths[0]).then((b) => {
          uni.showLoading({
            title: "加载中...",
            mask: true,
          });
          client
            .put(dir + filename, b)
            .then((res) => {
              this.userInfoForUpd.avatar = res.url;
              uni.showToast({
                title: "上传成功",
                duration: 1000,
              });
            })
            .catch((err) => {
              console.log(err);
              uni.hideToast();
              uni.showToast({
                title: "网络忙，上传失败",
                icon: "none",
              });
            });
        });
      });
    },
    viewImage(e) {
      uni.previewImage({
        urls: [this.imgInfo],
        current: e.currentTarget.dataset.url,
      });
    },
    h5UrlToBlob(url) {
      return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", url, true);
        xhr.responseType = "blob";
        xhr.onload = function (e) {
          if (this.status == 200) {
            var blob = this.response;
            // console.log(myBlob)
            resolve(blob);
            // myBlob现在是对象URL指向的blob。
          }
        };
        xhr.send();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
